package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.common.BaseContext;
import com.itheima.common.CustomException;
import com.itheima.common.R;
import com.itheima.domain.AddressBook;
import com.itheima.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 地址信息增删改查
 */
@RestController
@Slf4j
@RequestMapping("/addressBook")
@Api(tags = "地址信息相关接口")
public class AddressController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增
     *
     * @param addressBook
     * @return
     */
    @ApiOperation(value = "新增地址信息")
    @PostMapping
    public R<AddressBook> save(HttpServletRequest request, @RequestBody AddressBook addressBook) {
        log.info("接收到的地址信息为:{}", addressBook);
        //获取登录用户信息
        Long user = (Long) request.getSession().getAttribute("user");
        //通过用户id获取当前用户下有没有地址信息
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(user != null, AddressBook::getUserId, user);
        List<AddressBook> list = addressBookService.list(queryWrapper);
        if (list == null || list.size() == 0) {
            //若无，则将当前地址信息设置为默认地址
            addressBook.setIsDefault(1);
        }
        //在地址信息中设置登录用户的id
        addressBook.setUserId(user);
        //添加地址信息
        addressBookService.save(addressBook);
        log.info("地址信息已添加");
        //将添加的地址信息返回
        return R.success(addressBook);
    }

//    /**
//     * 设置默认地址
//     *
//     * @param addressBook
//     * @return
//     */
//    @PutMapping("/default")
//    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook) {
//        //设置条件构造器
//        log.info("addressBook:{}", addressBook);
//        LambdaUpdateWrapper<AddressBook> queryWrapper = new LambdaUpdateWrapper<>();
//        queryWrapper.eq(addressBook != null, AddressBook::getUserId, BaseContext.getCurrentId());
//        queryWrapper.set(AddressBook::getIsDefault, 0);
//        List<AddressBook> list = addressBookService.list(queryWrapper);
//
//        addressBookService.update(queryWrapper);
//        addressBook.setIsDefault(1);
//        addressBookService.updateById(addressBook);
//        return R.success(addressBook);
//    }

    /**
     * 设置默认地址
     */
    @ApiOperation(value = "设置默认地址")
    @PutMapping("default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook) {
        log.info("addressBook:{}", addressBook);
        //获取当前地址信息
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        //通过用户id获取用户的所有地址信息
        wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        //将所有地址都设置为非默认地址
        wrapper.set(AddressBook::getIsDefault, 0);
        //SQL:update address_book set is_default = 0 where user_id = ?
        addressBookService.update(wrapper);
        //将当前地址设置为默认地址
        addressBook.setIsDefault(1);
        //SQL:update address_book set is_default = 1 where id = ?
        //更新信息
        addressBookService.updateById(addressBook);
        log.info("默认地址已重新设置");
        //返回当前地址信息
        return R.success(addressBook);
    }


    /**
     * 修改地址信息
     *
     * @param addressBook
     * @return
     */
    @ApiOperation(value = "修改地址信息")



    @PutMapping
    public R<AddressBook> setAddressBook(@RequestBody AddressBook addressBook) {
        //设置条件构造器
        log.info("addressBook:{}", addressBook);
//        LambdaUpdateWrapper<AddressBook> queryWrapper = new LambdaUpdateWrapper<>();
//        queryWrapper.eq(addressBook != null, AddressBook::getUserId,BaseContext.getCurrentId());
//        addressBookService.update(queryWrapper);
        addressBookService.updateById(addressBook);
        log.info("地址信息已修改");
        return R.success(addressBook);
    }

    /**
     * 根据id查询地址
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据ID查询地址")

//    @ApiImplicitParam(name = "id", value = "地址唯一id", readOnly = true)


    @GetMapping("/{id}")
    public R<AddressBook> get(@PathVariable Long id) {
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook != null) {
            log.info("地址信息已查询:{}", addressBook);
            return R.success(addressBook);
        }
        return R.error("地址查询失败");
    }

    /**
     * 查询默认地址
     *
     * @return
     */
    @ApiOperation(value = "查询默认地址")
    @GetMapping("default")
    public R<AddressBook> getDefault(HttpServletRequest request) {
        Long user = (Long) request.getSession().getAttribute("user");
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(user != null, AddressBook::getUserId, user);
        queryWrapper.eq(AddressBook::getIsDefault, 1);
        AddressBook addressBook = addressBookService.getOne(queryWrapper);
        if (addressBook != null) {
            log.info("查询默认地址成功,地址为：{}", addressBook);
            return R.success(addressBook);
        }
        return R.error("地址查询失败");
    }

    /**
     * 查询指定用户的全部地址
     *
     * @param addressBook
     * @return
     */
    @ApiOperation(value = "查询指定用户全部地址")
    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook, HttpServletRequest request) {
        Long user = (Long) request.getSession().getAttribute("user");
        log.info("addressBook:{}", addressBook);
        addressBook.setUserId(BaseContext.getCurrentId());
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(user != null, AddressBook::getUserId, user);
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> list = addressBookService.list(queryWrapper);
//        if (list != null) {
        log.info("全部地址查询成功，地址为:{}", list);
        return R.success(list);
//        }
//        return R.error("地址查询失败");
    }

    /**
     * 删除地址信息
     *
     * @return
     */
    @ApiOperation(value = "删除地址")

    @ApiImplicitParam(name = "ids", value = "多地址id", readOnly = true)

    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        for (Long id : ids) {
            AddressBook addressBook = addressBookService.getById(id);
            if (addressBook.getIsDefault() == 1) {
                throw new CustomException("默认地址不能删除");
            }
        }

        addressBookService.removeByIds(ids);
        return R.success("地址删除成功");
    }
}
